<template>
  <div class="app-container">
  
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            v-hasPerm="['member:grade:add']"
            type="success"
            icon="plus"
            @click="handleOpenDialog()"
          >
            新增
          </el-button>
          <!-- <el-button
v-hasPerm="['member:grade:delete']"
            type="danger"
            :disabled="selectIds.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button> -->
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="Lists"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >

        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="100" />
        <el-table-column prop="adName" label="广告商名称"  />
        <el-table-column prop="adGrade" label="广告商级别"  />
        <el-table-column prop="adFee" label="开通金额"  />
        <el-table-column prop="taskAward" label="任务奖励(积分)"  />
        <el-table-column prop="effectiveT" label="有效时间(天)"  />
        <!-- <el-table-column prop="sort" label="排序" />
        <el-table-column prop="createTime" label="创建时间" width="220" /> -->

        <el-table-column label="操作" fixed="right" align="left" width="250">
          <template #default="scope">
            <el-button
              v-hasPerm="['member:grade:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id,scope.row)"
            >
              编辑
            </el-button>
            <el-button
v-hasPerm="['member:grade:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>

        
      </el-table>

      <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData" :rules="rules" label-width="120px">
        
        <el-form-item label="广告商级别" prop="grade">
          <el-input v-model="formData.grade" placeholder="请输入广告商级别" />
        </el-form-item>

        <el-form-item label="广告商名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入广告商名称" />
        </el-form-item>
        <el-form-item label="广告商开通费用" prop="fee">
          <el-input v-model="formData.fee" placeholder="请输入广告商开通费用" />
        </el-form-item>
        <el-form-item label="任务奖励(积分)" prop="taskRward">
          <el-input v-model="formData.taskRward" placeholder="请输入任务奖励(积分)" />
        </el-form-item>
        <el-form-item label="有效时间(天)" prop="effectiveTime">
          <el-input v-model="formData.effectiveTime" placeholder="请输入有效时间(天)" />
        </el-form-item>
        
        <el-form-item label="状态" style="display: none;">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "会员等级",
  inheritAttrs: false,
});

import MemberAPI, { LevelVO, LevelForm } from "@/api/system/member.api";

// const queryFormRef = ref();
const FormRef = ref();

const total = ref(0);
const loading = ref(false);

const selectIds = ref<number[]>([]);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
});

const dialog = reactive({
  title: "",
  visible: false,
});

const Lists = ref<LevelVO[]>();
const formData = reactive<LevelForm>({
  id: undefined,
  name: "",
  grade: 0,
  fee: "",
  taskRward: "",
  effectiveTime: 0
});

const rules = reactive({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

// 查询
async function handleQuery() {
  console.log(queryParams)
  loading.value = true;
  try {
    queryParams.page = queryParams.pageNum;
    queryParams.limit = queryParams.pageSize;

    Lists.value = await MemberAPI.getLevelList(queryParams);

    total.value = Lists.value.length || 0;
  } finally {
    loading.value = false;
  }

  loading.value = false;
}

// 重置查询
// function handleResetQuery() {
//   queryFormRef.value.resetFields();
//   handleQuery();
// }

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开新增弹窗
 *
 * @param Id ID
 */
async function handleOpenDialog(Id?:string,data?:any) {

  dialog.visible = true;
  if (Id) {
    dialog.title = "修改";
    console.log(data)
    Object.assign(formData, data);
    formData.grade = data.adGrade
    formData.name = data.adName
    formData.fee = data.adFee
    formData.dataId = data.id
    formData.taskRward = data.taskAward
    formData.effectiveTime = data.effectiveT
  } else {
    dialog.title = "新增";
  }
}

// 提交表单
function handleSubmit() {
  FormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        //ElMessage.success("修改成功");
        MemberAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        //ElMessage.success("新增成功");
        MemberAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
      handleCloseDialog();
      handleQuery();
      loading.value = false
    }
  });
}

// 删除
function handleDelete(Id?: number) {
  const Ids = [Id || selectIds.value].join(",");

  if (!Ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ElMessage.success("删除成功");
      const id_json = {
        dataId: Ids,
      }
      MemberAPI.LEVEL_Delete_URL(id_json)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
